package com.springsecurity.config;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import com.springsecurity.bean.Permission;
import com.springsecurity.bean.User;
import com.springsecurity.common.enums.ExceptionEnums;
import com.springsecurity.common.exception.LgException;
import com.springsecurity.dao.PermissionDao;

@Component("rbacauthorityservice")
public class RbacAuthorityService {
	@Autowired
    private PermissionDao permissionDao;

    private Set<String> perimssionUrls = new HashSet<>();
    
    @PostConstruct
    public void initPerimssions() {
    	List<Permission> Permissions = (List<Permission>) permissionDao.findAll();
        perimssionUrls = Permissions.stream().map(Permission::getUrl).collect(Collectors.toSet());
    }
	public boolean hasPermission(HttpServletRequest request, Authentication authentication) {

		Object userInfo = authentication.getPrincipal();

		boolean hasPermission = false;

		if (userInfo instanceof User) {
			User user = (User) userInfo;

			String uri = request.getRequestURI();
			String uriPattern = ""; // 记录uri成功匹配的模板uri
			boolean flag = false;
			AntPathMatcher antPathMatcher = new AntPathMatcher();
			for (String url : perimssionUrls) {
				if (StringUtils.isNotBlank(url) && antPathMatcher.match(url, uri)) {
					flag = true;
					uriPattern = url;
					break;
				}
			}
			if (flag && user.getUrls().contains(uriPattern))
				hasPermission = true;
			else {
				hasPermission = false;
			}
			return hasPermission;
		} else {
			return false;
		}
	}
}
